package echat.future.cn.echat;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.Request;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.netease.nim.avchatkit.common.permission.MPermission;
import com.netease.nim.avchatkit.common.permission.annotation.OnMPermissionDenied;
import com.netease.nim.avchatkit.common.permission.annotation.OnMPermissionGranted;
import com.netease.nim.avchatkit.common.permission.annotation.OnMPermissionNeverAskAgain;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import echat.future.cn.echat.home.HomeFragment;
import echat.future.cn.echat.my.bean.UserStatus;
import echat.future.cn.echat.my.view.RechargeActivity;
import echat.future.cn.echat.netease.CheckSumBuilder;
import echat.future.cn.echat.netease.NeteaseLoginUtil;
import echat.future.cn.echat.message.MessageFragment;
import echat.future.cn.echat.my.MyFragment;
import echat.future.cn.echat.my.api.UserApi;
import echat.future.cn.echat.my.bean.UserBean;
import echat.future.cn.echat.my.bean.WithdrawAccount;
import echat.future.cn.echat.my.utils.HttpUtilsRequst;
import echat.future.cn.echat.my.utils.StatusBarUtils;
import echat.future.cn.echat.my.utils.UserHelper;
import echat.future.cn.echat.video.VideoParentFragment;
import lumingweihua.future.cn.baselibgxh.base.BaseActivity;
import lumingweihua.future.cn.baselibgxh.base.FutureApi;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.network.AbstractRequest;
import lumingweihua.future.cn.baselibgxh.network.BeanRequest;
import lumingweihua.future.cn.baselibgxh.network.JsonElementRequest;
import lumingweihua.future.cn.baselibgxh.network.NetworkManager;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.DefaultMamahaoServerError;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;
import lumingweihua.future.cn.baselibgxh.utils.CommonUtils;
import lumingweihua.future.cn.baselibgxh.utils.Constant;
import lumingweihua.future.cn.baselibgxh.utils.DownloadHelper;
import lumingweihua.future.cn.baselibgxh.utils.MD5;
import lumingweihua.future.cn.baselibgxh.utils.SharedPreference;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MainActivity extends BaseActivity implements AMapLocationListener {

    private Fragment[] fragmentPages;
    private TextView[] tv_tabs;
    private int[] tab_icons;
//    private View[] tab_divisder;
    private AMapLocationClient mlocationClient;//定位客户端
    public static MainActivity mainActivity;

//    MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCCvnYlv6sra8ijaqAs8tOwAvR2IJjTjZS2LHVdpu46MYA2RLVi7qXrDJX45wdM7Y91zATfL/2P0DZGfzndOlvkvvOBvVqKFddSDb2cmqYJyEbTzJFbTaBz722YgsL0JofnQ42TfsvCH2A1ToWD7vO3/HQCwjOhmc+fbEhszAnjNdhn9upRUVCJQSlDfUfCIadQ155V5CqUiUeTRRP5ZmMN6pegHje8Y4s2qRDZjrg2FPcaykxEBUAikr3lLRKGBygleTrulGZEQPFV+UGJa7vpB//NlT6detdAo9N70/5tVFgaE0PXVh7IzNpaclcLUFnmavCeE5mspNODMelwZq93AgMBAAECggEAGEAzsfTHTxqC8KzKYQv5b+Bcb7zEHBlayB+e9WwNLAYaffZonp0dcWe4OZ7An+hAf90D2lIQeihoqNLYbMxyVw+EI0B4FrzOX43k6bNVsOLRIGAFZiYT6O00KuG2P4sWEjNZg041hSBEvB6Ab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    protected void initView() {
        //设置整个MainActivity为FullActivity 并且状态栏透明，导航栏隐藏
        setContentView(R.layout.activity_main);
        StatusBarUtils.hideStatus(this);
    }
    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    private VideoParentFragment videoParentFragment;
    @Override
    protected void initData() {
        mainActivity = this;
        videoParentFragment = new VideoParentFragment();
        fragmentPages = new Fragment[]{new HomeFragment(), videoParentFragment, new MessageFragment(),new MyFragment()};
        loadWithrawAccoount();
        premissions();
        requestOnline();

        //底部tab
        tv_tabs = new TextView[]{findTextView(R.id.tab_home),
                findTextView(R.id.tab_video),
                findTextView(R.id.tab_message),
                findTextView(R.id.tab_my)};

        tab_icons = new int[]{R.mipmap.tab_xin_xu,
                R.mipmap.tab_ship_xu,
                R.mipmap.tab_pl_xu,
                R.mipmap.tab_wode_xu,
                R.mipmap.tab_xin,
                R.mipmap.tab_ship,
                R.mipmap.tab_pl,
                R.mipmap.tab_wode
        };
//        tab_divisder = new View[]{
//                findViewById(R.id.tab_home_divider),
//                findViewById(R.id.tab_video_divider),
//                findViewById(R.id.tab_message_divider),
//                findViewById(R.id.tab_my_divider),
//        };

        for (TextView tv : tv_tabs)
            tv.setOnClickListener(this);

        // 添加显示第一个fragment
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, fragmentPages[0]).commit();

//        System.out.println(CheckSumBuilder.getCheckSum("dcc097b37661", "123456" ,"1540385918"));
//        if(TextUtils.isEmpty(MyApplication.getInstance().getNeteaseToken())){
            //判断是否登录了网易账号

//        }

        if(MyApplication.getInstance().isUserLogin())
            imLogin();

        mlocationClient = new AMapLocationClient(this);

        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置为高精度定位模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        mLocationOption.setInterval(5000);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);

        mlocationClient.startLocation();

//        时间戳---1540813111---礼物ID---13---sign---5ed850c99517e4d144984498e8037b5a

//        beginMsg.addBody(body);
//        beginMsg.setTo("15968170752");
//        EMClient.getInstance().chatManager().sendMessage(beginMsg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainActivity = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestEmoney();
        requestVersion();
        NeteaseLoginUtil neteaseLoginUtil = new NeteaseLoginUtil(MyApplication.getInstance().getPhone());
//            NeteaseLoginUtil neteaseLoginUtil = new NeteaseLoginUtil("15876542461");
        neteaseLoginUtil.loginNetease(context);
    }

    private static final int BASIC_PERMISSION_REQUEST_CODE = 100;
    private void premissions() {
        MPermission.printMPermissionResult(true, this, BASIC_PERMISSIONS);
        MPermission.with(MainActivity.this)
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
        try {
//            Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        try {
            Toast.makeText(this, "未全部授权，部分功能可能无法正常运行！", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    @Override
    protected void processClick(View v) {
        switch (v.getId()) {
            case R.id.tab_home:
                changeTab(0);
                break;
            case R.id.tab_video:
                changeTab(1);
                break;
            case R.id.tab_message:
                changeTab(2);
                break;
            case R.id.tab_my:
                changeTab(3);
                break;

            default:
                break;
        }
    }

    private int currentTabIndex;

    /**
     * 切换tab
     *
     * @param index
     */
    @SuppressWarnings("deprecation")
    public void changeTab(int index) {
        //当前tab不执行操作
        if (currentTabIndex == index)
            return;

//        tab_divisder[currentTabIndex].setVisibility(View.GONE);
//        tab_divisder[index].setVisibility(View.VISIBLE);

//        //切换之前选中tab的图标和文字颜色
//        tv_tabs[currentTabIndex].setTextColor(getResources().getColor(
//                R.color.C7));
        tv_tabs[currentTabIndex].setCompoundDrawables(CommonUtils.GetDrawable(
                context, tab_icons[currentTabIndex]), null, null, null);
//        //切换当前选中tab的图标和文字颜色
//        tv_tabs[index].setTextColor(getResources().getColor(
//                R.color.title_bg));
        tv_tabs[index].setCompoundDrawables(CommonUtils.GetDrawable(
                context, tab_icons[index + tv_tabs.length]), null, null, null);

        FragmentTransaction ft = getSupportFragmentManager()
                .beginTransaction();
        ft.hide(fragmentPages[currentTabIndex]);
        if (!fragmentPages[index].isAdded()) {
            ft.add(R.id.fragment_container, fragmentPages[index]);
        }
        ft.show(fragmentPages[index]).commit();

        if(currentTabIndex == 1 && index != 1)
            videoParentFragment.pause();

        currentTabIndex = index;
        if(currentTabIndex == 3) {
            try {
                ((MyFragment) fragmentPages[currentTabIndex]).refreshUser();
            }catch (Exception e){}
        }
    }


    private int mBackKeyPressedTimes = 0;

    @Override
    public void onBackPressed() {

        if (NiceVideoPlayerManager.instance().onBackPressd()) return;

        if (mBackKeyPressedTimes == 0) {
            showToast("再按一次退出APP");
            mBackKeyPressedTimes = 1;
            new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        mBackKeyPressedTimes = 0;
                    }
                }
            }.start();
            return;

        } else {
//            AppManager.getInstance().finishAllActivity();
            requestOffline();
            finish();
        }
        super.onBackPressed();
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 在 onStop 时释放掉播放器
//        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
    }

    /**
     * 获得提现账户
     */
    private void loadWithrawAccoount(){
        new HttpUtilsRequst<>(this,HttpUtilsRequst.retrofitClient.create(UserApi.class).getWithdrawAccount(UserHelper.getToken()),false)
                .setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<WithdrawAccount>) o -> {
                    UserHelper.setAccount(o);
                }).start();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                MyApplication.getInstance().setCity(aMapLocation.getCity());
                mlocationClient.stopLocation();
            } else {
//                mlocationClient.stopLocation();
//                Toast.makeText(this,"定位失败",Toast.LENGTH_LONG).show();
            }
        }
    }

    private final int REQUEST_DATAS = 6;
    private final int REQUEST_VERSION = 1;
    private final int REQUEST_ONLINE = 2;
    private final int REQUEST_OFFLINE = 3;

    public void requestEmoney() {
        // TODO Auto-generated method stub
        BeanRequest<UserBean, MamaHaoServerError> req = new BeanRequest<>(
                context,
                "/api/user/anchor_info"+"?token="+UserHelper.getToken() ,
                this,
                UserBean.class);

        req.setParam("token", UserHelper.getToken());
        req.setParam("time", "1540868162");
        String key = "9b4aaf?&&##664bdef@c3fc3efa9";
        req.setParam("sign", MD5.Md5(System.currentTimeMillis()/1000+key).toLowerCase());

        addRequestQueue(req, REQUEST_DATAS);

    }

    /**
     * 请求登录
     */
    private void requestVersion() {

        BeanRequest<UpdateVersion, MamaHaoServerError> req = new BeanRequest<>(
                context,
                "/api/user/version" ,
                this,
                UpdateVersion.class);

        req.setParam("token", UserHelper.getToken());

        addRequestQueue(req, REQUEST_VERSION);
    }

    /**
     * 接听状态
     */
    private void requestOnline() {

        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "/api/send_anchor_status", this);

        req.setParam("member_id", SharedPreference.getString(context,"uid"));
        req.setParam("status", "1");

        addRequestQueue(req, REQUEST_ONLINE);
    }

    /**
     * 取消接听状态
     */
    private void requestOffline() {

        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "/api/send_anchor_status", this);

        req.setParam("member_id", SharedPreference.getString(context,"uid"));
        req.setParam("status", "0");

        addRequestQueue(req, REQUEST_OFFLINE);
    }

    @Override
    protected void onResponseSuccess(ReqTag tag, Object data) {
        super.onResponseSuccess(tag, data);
        switch (tag.getReqId()) {
            case REQUEST_DATAS:
                MyApplication.getInstance().e_money = ((UserBean)data).getE_money();
                MyApplication.getInstance().isZhubo = ((UserBean)data).getUser_role()==3;
                MyApplication.getInstance().isXianmian = ((UserBean)data).getFirst_free()==1;
                break;
            case REQUEST_VERSION:
                //版本信息
                try {
                    UpdateVersion updateVersion = (UpdateVersion)data;
                    //版本信息
                    if(!updateVersion.getApp_version().equals(CommonUtils.getAppVersionCode(context)))
                        alertUpdate(updateVersion.getDescription(),updateVersion.getDownloadurl());
                } catch (Exception e) {
                    // TODO: handle exception
                }

                break;

            default:
                break;
        }
    }

    @Override
    protected void onResponseFailure(ReqTag tag, MamaHaoServerError error, AbstractRequest.MamaHaoError clientError) {
        super.onResponseFailure(tag, error, clientError);
    }

    /**
     * 环信登录
     */
    private void imLogin() {                               //登录

        EMClient.getInstance().login(SharedPreference.getString(context,"phone"), "123456", new EMCallBack() {

            @Override
            public void onSuccess() {
                Log.v("环信登录成功", "登陆成功 = "+SharedPreference.getString(context,"phone"));
                EMClient.getInstance().chatManager().loadAllConversations();
                EMClient.getInstance().groupManager().loadAllGroups();

                //get easeui instance
//                EaseUI easeUI = EaseUI.getInstance();
//                //需要EaseUI库显示用户头像和昵称设置此provider
//                easeUI.setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {
//
//                    @Override
//                    public EaseUser getUser(String username) {
//                        EaseUser eu= getUserInfo(username);
//                        eu.setAvatar(UserHelper.getUser().getAvatar());
//                        eu.setNickname(UserHelper.getUser().getUsername());
//                        return eu;
//                    }
//                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String error) {
                Log.v("环信登录失败", "登录失败 = "+code + error);
                if(code == 204){
                    imRegister();
                }
            }
        });


    }

    /**
     * 环信注册
     */
    private void imRegister() {
        new Thread(new Runnable() {                              //注册
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(SharedPreference.getString(context,"phone"), "123456");
                    imLogin();
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    Log.v("环信finishregister", "注册失败" + e.getErrorCode() + "   $$" + e.getMessage());
                }
            }
        }).start();

    }

    public void gotoCharge(){
        startActivity(new Intent(this,RechargeActivity.class));
    }

    public class UpdateVersion{
        private String versioncode;
        private String downloadurl;
        private String description;
        public String getApp_version() {
            return versioncode;
        }
        public void setApp_version(String app_version) {
            this.versioncode = app_version;
        }
        public String getDownloadurl() {
            return downloadurl;
        }
        public void setDownloadurl(String downloadurl) {
            this.downloadurl = downloadurl;
        }
        public String getDescription() {
            return description;
        }
        public void setDescription(String description) {
            this.description = description;
        }

    }

    private ProgressDialog progressDialog;
    private File file;
    protected void alertUpdate(String msg,final String url) {
        // TODO Auto-generated method stub
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请更新到最新版本").setMessage(msg)
                .setCancelable(false);

        builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent intent= new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                startActivity(intent);
            }

        });
//        builder.setNegativeButton("下次", new DialogInterface.OnClickListener() {
//
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                // TODO Auto-generated method stub
//            }
//        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private final int ALERT_UPDATE = 0;
    private final int CONN_ERROR = 1;
    private final int INSTALL = 2;
    private final int FAIL_DOWNLOAD = 3;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case INSTALL:
                    install();
                    break;
                case CONN_ERROR:
                    Toast.makeText(getApplicationContext(), "网络连接失败",Toast.LENGTH_SHORT).show();
                    break;
                case FAIL_DOWNLOAD:
                    Toast.makeText(getApplicationContext(), "下载失败",Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    protected void install() {
        // TODO Auto-generated method stub
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        startActivity(intent);
    }

}
